package cn.falcon.fmobi.console.controller;

import cn.falcon.fmobi.biz.exception.AgentValidateException;
import cn.falcon.fmobi.biz.service.AgentService;
import cn.falcon.fmobi.biz.service.CustomerService;
import cn.falcon.fmobi.console.common.RestfulJsonModelAndView;
import cn.falcon.fmobi.console.common.Result;
import cn.falcon.fmobi.console.constant.ParamConstant;
import cn.falcon.fmobi.console.constant.UrlConstant;
import cn.falcon.fmobi.console.exception.CallBackException;
import cn.falcon.fmobi.console.exception.ParamValidateException;
import cn.falcon.fmobi.console.requestparam.AgentQueryParam;
import cn.falcon.fmobi.dao.model.AgentVo;
import cn.falcon.fmobi.dao.po.Agent;
import cn.falcon.fmobi.dao.util.DataUtils;
import cn.falcon.marketing.api.util.ValidateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by haojie.zhang
 * Time 2017/11/6.
 */


@Controller
@RequestMapping(UrlConstant.AGENT_URL)
public class AgentCtrl extends BaseCtrl {

    @Autowired
    private AgentService agentService;

    @Autowired
    private CustomerService customerService;

    /**
     * 代理商列表
     * @return
     */
    @RequestMapping(value = "/agentList", method = {RequestMethod.GET})
    public ModelAndView agentList(){
        return RestfulJsonModelAndView.buildJsonModelAndView(agentService.agentList());
    }

    /**
     * 代理商下是否有广告主
     * @param agentId
     * @return
     */
    @RequestMapping(value = "/getAdvertiser", method = {RequestMethod.GET})
    public ModelAndView getAdvertiser(Integer agentId) {

        Map<String, Integer> param = new HashMap<>();
        param.put("number", customerService.getAgent(agentId));
        return RestfulJsonModelAndView.buildJsonModelAndView(param);
    }

    /**
     * 代理商列表分页查询
     *
     * @param agentQueryParam
     * @return
     */
    @RequestMapping(value = "/selectAgentListPage", method = {RequestMethod.GET})
    public ModelAndView selectAgentListPage(AgentQueryParam agentQueryParam) {

        Map<String, Object> param = agentQueryParam.getSearch();

        return RestfulJsonModelAndView.buildJsonModelAndView(agentService.selectAgentListPage(param, agentQueryParam.getPageInfo()));
    }

    /**
     * 代理商详情
     *
     * @param agentId
     * @return
     */
    @RequestMapping(value = "/getAgent", method = {RequestMethod.GET})
    public ModelAndView getAgent(Integer agentId) {
        return RestfulJsonModelAndView.buildJsonModelAndView(agentService.getAgentById(agentId));
    }

    /**
     * 新建代理商
     *
     * @param agentVo
     * @return
     */
    @RequestMapping(value = "/addAgent", method = {RequestMethod.POST})
    public ModelAndView addAgent(@RequestBody AgentVo agentVo) throws ParamValidateException, UnsupportedEncodingException {
        this.check(agentVo);
        agentService.addAgent(agentVo);
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 编辑代理商
     *
     * @param agentVo
     * @return
     */
    @RequestMapping(value = "/editAgent", method = {RequestMethod.PUT})
    public ModelAndView editAgent(@RequestBody AgentVo agentVo) throws ParamValidateException, UnsupportedEncodingException {
        this.check(agentVo);
        agentService.editAgent(agentVo);
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 新建修改参数验证
     * @param agentVo
     * @throws UnsupportedEncodingException
     * @throws ParamValidateException
     */
    public void check(AgentVo agentVo) throws UnsupportedEncodingException ,ParamValidateException{
        //代理商名称必填
        if (StringUtils.isEmpty(agentVo.getName())) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER, "agent_name", "Result.err.miss.parameter");
        }
        if (null != agentVo.getId()) {
            int result = agentService.countName(agentVo.getName(), agentVo.getId());
            if (result > 0) {
                throw new CallBackException(AgentValidateException.ErrorCode.AGENT_NAME_NOT_NULL.getValue()
                        , AgentValidateException.ErrorCode.AGENT_NAME_NOT_NULL.getDesc());
            }
        }else{
            int result = agentService.countName(agentVo.getName(), null);
            if (result > 0) {
                throw new CallBackException(AgentValidateException.ErrorCode.AGENT_NAME_NOT_NULL.getValue()
                        , AgentValidateException.ErrorCode.AGENT_NAME_NOT_NULL.getDesc());
            }
        }

        //代理商名称最大字节60
        if (ValidateUtil.checkStrByteLengthMoreThan(agentVo.getName(), ParamConstant.AGENT_NAME_BUDGET_MAX)) {
            throw new ParamValidateException(Result.ERR_INVALID_LENGTH, "agent_name", "Result.err.invalid.length");
        }
        //状态必填
        if (DataUtils.isNull(agentVo.getStatus())) {
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER, "status", "Result.err.miss.parameter");
        }
        //提示服务费必须在0-99
        if (agentVo.getRebate() < 0 || agentVo.getRebate() > 99) {
            throw new CallBackException(AgentValidateException.ErrorCode.AGENT_REBATE_MAX_MIX_LIMIT.getValue()
                    , AgentValidateException.ErrorCode.AGENT_REBATE_MAX_MIX_LIMIT.getDesc());
        }
        if (null != agentVo.getId()) {
            Integer agentId = customerService.getAgent(agentVo.getId());
            if (agentId == 0) {
                //服务费必填，当该代理商没有广告主时可以修改，如果有广告主不可以修改
                if (DataUtils.isNull(agentVo.getRebate())) {
                    throw new ParamValidateException(Result.ERR_MISS_PARAMETER, "rebate", "Result.err.miss.parameter");
                }
            }else{
                //判断不能修改
                Agent agent = agentService.getAgentById(agentVo.getId());
                if (agentVo.getRebate() != agent.getRebate()) {
                    throw new CallBackException(AgentValidateException.ErrorCode.AGENT_REBATE_NOT_UPDATE.getValue()
                            , AgentValidateException.ErrorCode.AGENT_REBATE_NOT_UPDATE.getDesc());
                }
            }
        }else{
            if (DataUtils.isNull(agentVo.getRebate())) {
                throw new ParamValidateException(Result.ERR_MISS_PARAMETER, "rebate", "Result.err.miss.parameter");
            }
        }
        //联系人姓名最大字节20
        if (ValidateUtil.checkStrByteLengthMoreThan(agentVo.getLinkName(), ParamConstant.AGENT_LINK_NAME_BUDGET_MAX)) {
            throw new ParamValidateException(Result.ERR_INVALID_LENGTH, "link_name", "Result.err.invalid.length");
        }

        //手机最大字节20
        if (ValidateUtil.checkStrByteLengthMoreThan(agentVo.getPhoneNo(), ParamConstant.AGENT_PHONE_NO_BUDGET_MAX)) {
            throw new ParamValidateException(Result.ERR_INVALID_LENGTH, "phone_no", "Result.err.invalid.length");
        }

        //邮箱最大字节60
        if (ValidateUtil.checkStrByteLengthMoreThan(agentVo.getEmail(), ParamConstant.AGENT_EMAIL_BUDGET_MAX)) {
            throw new ParamValidateException(Result.ERR_INVALID_LENGTH, "email", "Result.err.invalid.length");
        }
    }
}
